/*
 * @lc app=leetcode.cn id=2047 lang=cpp
 *
 * [2047] 句子中的有效单词数
 */

// @lc code=start
class Solution
{
public:
    int isLetter(char c)
    {
        return (c >= 'a' && c <= 'z');
    }

    int isDigit(char c)
    {
        return (c >= '0' && c <= '9');
    }

    int isValid(string s)
    {
        int n = s.size();
        int hasHyphen = 0;
        for (int i = 0; i < n; i++)
        {
            char c = s[i];
            if (isDigit(c))
            {
                return 0;
            }
            else if (c == '-')
            {
                if (hasHyphen || i == 0 || i == n - 1 || !isLetter(s[i - 1]) || !isLetter(s[i + 1]))
                {
                    return 0;
                }
                hasHyphen = 1;
            }
            else if (c == '!' || c == '.' || c == ',')
            {
                if (i != n - 1)
                {
                    return 0;
                }
            }
        }
        return 1;
    }

    int countValidWords(string sentence)
    {
        int n = sentence.size();
        int ans = 0;
        int l = 0, r = 0;
        while (1)
        {
            while (l < n && sentence[l] == ' ')
            {
                l++;
            }
            if (l >= n)
            {
                break;
            }
            r = l + 1;
            while (r < n && sentence[r] != ' ')
            {
                r++;
            }
            string s = sentence.substr(l, r - l);
            if (isValid(s))
            {
                ans++;
            }
            l = r + 1;
        }
        return ans;
    }
};
// @lc code=end
